<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item  prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入优惠券名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['coupon:coupon:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['coupon:coupon:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['coupon:coupon:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['coupon:coupon:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="couponList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="优惠券ID" align="center" prop="id" />
      <el-table-column label="优惠券名称" align="center" prop="name" />
      <el-table-column label="商品使用范围" align="center" prop="desc" />
      <el-table-column label="满减金额" align="center" prop="tag" />
      <el-table-column label="优惠券数量" align="center" prop="total" >
        <template slot-scope="scope">
          {{scope.row.total == 0 ? "不限" : scope.row.total }}
        </template>
      </el-table-column>
      <el-table-column label="最低消费" align="center" prop="min" />
      <el-table-column label="每人限领" align="center" prop="limit">
        <template slot-scope="scope">
          {{scope.row.limit == 0 ? "不限" : "限领一张"}}
        </template>
      </el-table-column>
      <el-table-column label="优惠券类型" align="center" prop="type" >
        <template slot-scope="scope">
          {{scope.row.type==0 ? "通用领卷":scope.row.type==1 ? "注册赠券":"优惠券码兑换"}}
        </template>
      </el-table-column>
      <el-table-column label="优惠券状态" align="center" prop="status" >
        <template slot-scope="scope">
          {{scope.row.status==0 ? "正常可用":scope.row.status==1 ? "过期":"下架"}}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handletiaozhuan(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['coupon:coupon:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['coupon:coupon:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改优惠券管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="优惠券名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入优惠券名称" />
        </el-form-item>
        <el-form-item label="介绍" prop="desc">
          <el-input v-model="form.desc" placeholder="请输入优惠券介绍" />
        </el-form-item>
        <el-form-item label="标签" prop="tag">
          <el-input v-model="form.tag" placeholder="请输入标签" />
        </el-form-item>
        <el-form-item label="最低消费" prop="min">
          <el-input type="number" min="0" v-model="form.min" placeholder="请输入最低消费" />
        </el-form-item>
        <el-form-item label="满减金额" prop="discount">
          <el-input type="number" min="0" v-model="form.discount" placeholder="请输入满减金额" />
        </el-form-item>
        <el-form-item label="每人限领" prop="limit">
          <el-input type="number" min="0" v-model="form.limit" placeholder="请输入每人限领" />
        </el-form-item>
        <el-form-item label="发布类型" prop="type">
          <el-select v-model="form.type">
            <el-option
              v-for="isho in limits"
              :key="isho.id"
              :label="isho.value"
              :value="isho.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="优惠券数量" prop="total">
          <el-input type="number" min="0" value="0" v-model="form.total" placeholder="请输入优惠券数量" />
        </el-form-item>
        <el-form-item label="有效期" prop="days">
          <!-- 切换按钮 -->
          <el-radio-group v-model="timeType">
            <el-radio :label="0">领券相对天数</el-radio>
            <el-radio :label="1">指定绝对时间</el-radio>
          </el-radio-group>
          <!-- 根据类型显示不同输入 -->
          <div v-if="timeType === 0">
            <el-input
              v-model="form.days"
              placeholder="请输入有效期/天"
              style="width: 200px; margin-top: 10px;"
            />
          </div>
          <div v-else>
            <el-date-picker
              v-model="startTime"
              type="datetime"
              placeholder="选择开始时间"
              style="width: 200px; margin-right: 10px; margin-top: 10px;"
            />
            <el-date-picker
              v-model="endTime"
              type="datetime"
              placeholder="选择结束时间"
              style="width: 200px; margin-top: 10px;"
            />
          </div>
        </el-form-item>
        <el-form-item label="商品限制范围" prop="type">
          <el-select v-model="form.goodsType">
            <el-option
              v-for="isho in types"
              :key="isho.id"
              :label="isho.value"
              :value="isho.id"
            ></el-option>
          </el-select>
        </el-form-item>
        </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCoupon, getCoupon, delCoupon, addCoupon, updateCoupon } from "@/api/popularize/coupon";

export default {
  name: "Coupon",
  data() {
    return {
      limits: [
        { id : 0 , value: '通用领卷'},
        { id : 1 , value: '注册赠卷'},
        { id : 2 , value: '兑换码'},
      ],
      types: [
        { id : 0 , value: '全场通用'},
        { id : 1 , value: '指定分类'},
        { id : 2 , value: '指定商品'},
      ],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 优惠券管理表格数据
      couponList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        type: null,
        status: null,
      },
      // 有效期类型：0-领券相对天数  1-指定绝对时间，默认相对天数
      timeType: 0,
      // 绝对时间开始（领券后绝对时间场景下用，比如选固定起止时间）
      startTime: null,
      // 绝对时间结束
      endTime: null,
      // 表单参数
      form: {
        name: '',         // 优惠券名称
        desc: '',         // 介绍
        tag: '',          // 标签
        min: 0,           // 最低消费
        discount: 0,      // 满减金额
        limit: 1,         // 每人限领
        type: '',         // 发布类型
        total: 0,         // 优惠券数量
        days: '',         // 有效期/天
        goodsType: ''     // 商品限制范围
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "优惠券名称不能为空", trigger: "blur" }
        ],
        total: [
          { required: true, message: "优惠券数量不能为空", trigger: "blur" }
        ],
        days: [
            {
              validator: (rule, value, callback) => {
                if (this.timeType === 0) {
                  if (!value || value < 0) {
                    callback(new Error('相对天数需大于等于 0'));
                  } else {
                    callback();
                  }
                } else {
                  // 绝对时间模式，校验 start/end
                  if (!this.startTime || !this.endTime) {
                    callback(new Error('请选择完整的绝对时间区间'));
                  } else if (this.startTime > this.endTime) {
                    callback(new Error('开始时间不能晚于结束时间'));
                  } else {
                    callback();
                  }
                }
              },
              trigger: 'blur'
            }
          ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询优惠券管理列表 */
    getList() {
      this.loading = true;
      listCoupon(this.queryParams).then(response => {
        this.couponList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
          id: null,
          name: null,
          desc: null,
          tag: null,
          total: 0,
          discount: 0,
          min: 0,
          limit: 1,
          type: null,
          status: null,
          goodsType: null,
          goodsValue: null,
          code: null,
          timeType: 0, // 重置为相对天数
          days: null,
          startTime: null,
          endTime: null,
          addTime: null,
          updateTime: null,
          deleted: null
        };
        this.timeType = 0; // 重置切换状态
        this.startTime = null;
        this.endTime = null;
        this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加优惠券管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getCoupon(id).then(response => {
        const data = response.data;
        this.form = data;
        // 回显有效期类型、绝对时间
        this.timeType = data.timeType;
        this.startTime = data.startTime;
        this.endTime = data.endTime;
        this.open = true;
        this.title = "修改优惠券管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 整理要提交的参数
          const submitData = {
            ...this.form,
            timeType: this.timeType,
            startTime: this.startTime,
            endTime: this.endTime
          };
          if (this.form.id != null) {
            updateCoupon(submitData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCoupon(submitData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除优惠券管理编号为"' + ids + '"的数据项？').then(function() {
        return delCoupon(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 跳转到优惠卷详情页 */
    handletiaozhuan(row){
          this.$router.push({
            path: '/coupon/couponXiangQing',
            query: {
              id: row.id,
            }
          })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('coupon/coupon/export', {
        ...this.queryParams
      }, `coupon_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
